<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { onMounted, watch, ref } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  historical: Array, // [{ds, y}]
  forecast: Array    // [{ds, yhat}]
})

const chartRef = ref(null)
let chartInstance = null

const renderChart = () => {
  if (!props.historical || !props.forecast) return
  const histDates = props.historical.map(item => item.ds)
  const histPrices = props.historical.map(item => item.y)
  const forecastDates = props.forecast.map(item => item.ds)
  const forecastPrices = props.forecast.map(item => item.yhat)

  // 找到历史和预测的分界点
  const splitIndex = forecastDates.findIndex(ds => ds > histDates[histDates.length - 1])
  const forecastPartDates = forecastDates.slice(splitIndex)
  const forecastPartPrices = forecastPrices.slice(splitIndex)

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['历史收盘价', '预测收盘价'] },
    grid: { left: '8%', right: '8%', bottom: '15%' },
    xAxis: { type: 'category', data: [...histDates, ...forecastPartDates] },
    yAxis: { type: 'value', name: '价格' },
    series: [
      {
        name: '历史收盘价',
        type: 'line',
        data: histPrices,
        showSymbol: false,
        lineStyle: { color: '#5470C6', width: 2 }
      },
      {
        name: '预测收盘价',
        type: 'line',
        data: Array(histPrices.length - 1).fill(null).concat([histPrices[histPrices.length - 1], ...forecastPartPrices]),
        showSymbol: false,
        lineStyle: { color: '#91cc75', type: 'dashed', width: 2 }
      }
    ]
  }
  chartInstance?.setOption(option)
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  renderChart()
})

watch(() => [props.historical, props.forecast], renderChart, { deep: true })
</script> 